package cn.com.ytst.data.integration.util.http;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ytst.framework.common.exception.BusinessException;

public class HttpUtil {

	
	private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
	
	private static int socketTimeout = 10000;  
	private static int connectTimeout = 1000;  
	private static int connectionRequestTimeout = 10000;  
	private static int maxConnTotal = 300;   //最大不要超过1000  
	private static int maxConnPerRoute = 20;//实际的单个连接池大小，如tps定为50，那就配置50 
	
	private static final String ENCODE = "utf-8";
	
	private static final String CONTENT_TYPE_VALUE = "application/json;charset="+ENCODE;

	private static final String CONTENT_TYPE_KEY = "Content-Type";

	private static final String ACCESS_TOKEN_KEY = "Access-Token";

	private static final String CONTENT_TYPE_TEXT_JSON = "text/json";
	
	@SuppressWarnings("deprecation")
	public static String post(String url)  {
		 String result = "";
		 HttpPost  post = new HttpPost (url);
		 CloseableHttpClient httpclient = getCloseableHttpClient();
	      
	     try {
			HttpResponse response = httpclient.execute(post);
		    result = EntityUtils.toString(response.getEntity() , ENCODE).trim();
		    
		} catch (Exception e) {
				e.printStackTrace();
		}finally{
			post.releaseConnection();
			httpclient.getConnectionManager().shutdown(); 
		}
		return result;
	}

	@SuppressWarnings("deprecation")
	public static String postEntity(String url, Map<String, String> argsMap)  {
    
		 String result = "";
		 HttpPost  post = new HttpPost (url);
		 CloseableHttpClient httpclient = getCloseableHttpClient();
		
	     List<NameValuePair> nvps = new ArrayList<>();
	     for(Map.Entry<String, String> entry :argsMap.entrySet()){
	    	 nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
	     }
	     try {
		    post.setEntity(new UrlEncodedFormEntity((List<? extends org.apache.http.NameValuePair>) nvps, ENCODE));
			HttpResponse response = httpclient.execute(post);
		    result = EntityUtils.toString(response.getEntity() , ENCODE).trim();
		    
		} catch (Exception e) {
				logger.error("",e);
				 throw new BusinessException("402",com.ytst.framework.common.Constants.ERROR_FLAGE,e.fillInStackTrace());
		}finally{
			post.releaseConnection();
			httpclient.getConnectionManager().shutdown();  
		}
		return result;
		

	}
	
	public static CloseableHttpClient getCloseableHttpClient(){
		
		RequestConfig config = RequestConfig.custom()  
		         .setSocketTimeout(socketTimeout)  
		         .setConnectTimeout(connectTimeout)  
		         .setConnectionRequestTimeout(connectionRequestTimeout).build();  
		PoolingHttpClientConnectionManager poolConnManager = new PoolingHttpClientConnectionManager();
		poolConnManager.setMaxTotal(maxConnTotal);
		poolConnManager.setDefaultMaxPerRoute(maxConnPerRoute);
		return HttpClients.custom().setDefaultRequestConfig(config).setConnectionManager(poolConnManager).build();
		
	}

	@SuppressWarnings("deprecation")
	public static String get(String url) throws Exception {
		 String result = "";
		 HttpGet  get = new HttpGet (url);
		 CloseableHttpClient httpclient = getCloseableHttpClient();
	     try {
			HttpResponse response = httpclient.execute(get);
		    result = EntityUtils.toString(response.getEntity() , ENCODE).trim();
		    
		} catch (Exception e) {
				e.printStackTrace();
		}finally{
			get.releaseConnection();
			httpclient.getConnectionManager().shutdown();  
		}
		return result;	
	}

	/**
	 * 以http以非表单形式调用，客户端传入json格式的数据
	 * @param url
	 * @param json
	 * @param token
	 * @return
	 */
	public  static String postMethodJsonEntity(String url, String json,String token)  {

		String result = "";
		HttpPost  post = new HttpPost (url);
		post.addHeader(ACCESS_TOKEN_KEY,token);
		post.setHeader(CONTENT_TYPE_KEY, CONTENT_TYPE_VALUE);
		CloseableHttpClient httpclient = getCloseableHttpClient();

		try {
			StringEntity se = new StringEntity(json);
			se.setContentType(CONTENT_TYPE_TEXT_JSON);
			post.setEntity(se);
			HttpResponse response = httpclient.execute(post);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString( entity, "utf-8").trim();
			//EntityUtils.consume(entity);
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			post.releaseConnection();

			httpclient.getConnectionManager().shutdown();
		}
		return result;


	}

	
	
}
